import Vue from 'vue'
import VueRouter from 'vue-router'
import { menuList } from '@/utils/menuList'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import(/* webpackChunkName: "about" */ '../views/Home.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由拦截
router.beforeEach((to, from, next) => {
  console.log('menuList---', store.state.routers, to, from)
  // var data = routerData(menuList)
  console.log('res---', !store.state.routers.length)
  if (!(store.state.routers && store.state.routers.length)) {
    var data = routerData(menuList)
    router.addRoutes(data)
  }
  store.dispatch('SETNAV', menuList)
  next()
})
function routerData(resutl) {
  resutl.forEach(item => {
    routes.push({
      path: item.path,
      name: item.name,
      component: () => import(`../views/${item.component}`),
      children: item.children
    })
  })
  return routes
}

export default router
